package base.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import app.util.StringUtil;

public class MenuTreeChecked {
	
	public static String root = "root";
	
	private Object children;
	
	private MenuTreeNodeChecked menuTreeNodeChecked;

	public MenuTreeNodeChecked getMenuTreeNodeChecked() {
		return menuTreeNodeChecked;
	}

	public void setMenuTreeNodeChecked(MenuTreeNodeChecked menuTreeNodeChecked) {
		this.menuTreeNodeChecked = menuTreeNodeChecked;
	}

	/**
	 * 建树
	 * @param dateList
	 * @param MenuTreeNodeCheckedNameKey
	 * @param treeParentKey
	 */
	public void buildTree(List<Map<String, Object>> dateList, String MenuTreeNodeCheckedNameKey, String treeParentKey){
		List<MenuTreeNodeChecked> MenuTreeNodeCheckedList = new ArrayList<MenuTreeNodeChecked>();
		for (int i = 0; dateList!=null && i < dateList.size(); i++) {
			Map<String, Object> map = dateList.get(i);
			MenuTreeNodeChecked menuTreeNodeChecked = new MenuTreeNodeChecked();
			menuTreeNodeChecked.setId(StringUtil.objectToStr(map.get("id")));
			menuTreeNodeChecked.setText(StringUtil.objectToStr(map.get(MenuTreeNodeCheckedNameKey)));
			menuTreeNodeChecked.setParentId(StringUtil.objectToStr(map.get(treeParentKey)));
			menuTreeNodeChecked.setMenuClass(StringUtil.objectToStr(map.get("menuClass")));
			menuTreeNodeChecked.setMenuCode(StringUtil.objectToStr(map.get("menuCode")));
			menuTreeNodeChecked.setLeaf(true);
			menuTreeNodeChecked.setIsUse((int)map.get("isUse"));
			MenuTreeNodeCheckedList.add(menuTreeNodeChecked);
		}
		
		List<MenuTreeNodeChecked> rootTrees = new ArrayList<MenuTreeNodeChecked>();
		
        for (MenuTreeNodeChecked MenuTreeNodeChecked : MenuTreeNodeCheckedList) {
            if(root.equals(MenuTreeNodeChecked.getParentId())){
            	rootTrees.add(MenuTreeNodeChecked);
            }
            for (MenuTreeNodeChecked t : MenuTreeNodeCheckedList) {
                if(t.getParentId().equals(MenuTreeNodeChecked.getId())){
                    if(MenuTreeNodeChecked.getChildren() == null){
                        List<MenuTreeNodeChecked> myChildrens = new ArrayList<MenuTreeNodeChecked>();
                        myChildrens.add(t);
                        MenuTreeNodeChecked.setLeaf(false);
                        MenuTreeNodeChecked.setChildren(myChildrens);
                    }else{
                    	MenuTreeNodeChecked.setLeaf(false);
                        MenuTreeNodeChecked.getChildren().add(t);
                    }
                }
            }
        }
        this.setChildren(rootTrees);
	}
	
	public Object getChildren() {
		return children;
	}

	public void setChildren(Object children) {
		this.children = children;
	}

}
